import React, { Component } from 'react'
import { Form, Select, Input, Button, message } from 'antd';
import axios from 'axios';
const FormItem = Form.Item;
const Option = Select.Option;

class Register extends Component {
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        values.gender = values.gender === 'male';
        const res = axios.post('http://localhost:8000/register', values);
        Promise.resolve(res).then((rtn) => {
          const data = rtn.data || {};
          if (data && data.success) {
            message.success(data.msg);
            // 进行页面之间的跳转，前提是使用了BrowserRouter盒子
            this.props.history.push('/');
          } else {
            message.error(data.msg);
          }
        })
      }
    })
  }
  
  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSubmit}>
        <FormItem
          label="姓名"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 8 }}
        >
          {getFieldDecorator('name', {
            rules: [{ required: true, message: '请输入姓名' }],
          })(
            <Input placeholder="请输入姓名" />
          )}
        </FormItem>
        <FormItem
          label="密码"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 8 }}
        >
          {getFieldDecorator('pwd', {
            rules: [{ required: true, message: '请输入密码' }],
          })(
            <Input placeholder="请输入密码" type="password" />
          )}
        </FormItem>
        <FormItem
          label="性别"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 8 }}
        >
          {getFieldDecorator('gender', {
            rules: [{ required: true, message: '请选择性别' }],
          })(
            <Select
              placeholder="请选择性别"
              onChange={this.handleSelectChange}
            >
              <Option value="male">男</Option>
              <Option value="female">女</Option>
            </Select>
          )}
        </FormItem>
        <FormItem
          label="手机号"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 8 }}
        >
          {getFieldDecorator('mobile', {
            rules: [{ required: true, message: '请输入手机号' }],
          })(
            <Input placeholder="请输入手机号" />
          )}
        </FormItem>
        <FormItem
          wrapperCol={{ span: 12, offset: 5 }}
        >
          <Button type="primary" htmlType="submit">注册</Button>
        </FormItem>
      </Form>
    );
  }
}
export default Form.create()(Register);
